import socket

from utility.LogHelper import LogHelper


class UDPHelper:
    def __init__(self, slef_address: tuple = (None, None), dest_address: tuple = (None, None), buf_size=1024):
        self.SELF_ADDRESS = slef_address
        self.DEST_ADDRESS = dest_address
        self.BUFSIZ = buf_size

        self.log_helper = LogHelper()

        self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_client.bind(self.SELF_ADDRESS)
        self.udp_client.settimeout(10)

    def recv_message(self):
        while True:
            try:
                recv_msg, send_addr = self.udp_client.recvfrom(self.BUFSIZ)
                if recv_msg:
                    # 自动设置将要发送的对象地址
                    self.DEST_ADDRESS = send_addr
                    return recv_msg, send_addr
            except socket.timeout:
                self.log_helper.error("udp receive time out")
                continue

    def on_recv_message(self):
        while True:
            try:
                recv_msg, send_addr = self.udp_client.recvfrom(self.BUFSIZ)
                return recv_msg,send_addr
            except socket.timeout:
                self.log_helper.error("receive time out")
                continue

    def send_message(self, message):
        self.udp_client.sendto(message, self.DEST_ADDRESS)

    def send_message_to_dest(self, message, dest_address):
        self.udp_client.sendto(message, dest_address)

    def send_broadcast_message(self, message, port):
        network = '<broadcast>'
        port = port
        # 发送广播配置
        self.udp_client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.udp_client.sendto(message, (network, port))

    def close_udp(self):
        self.udp_client.close()